package com.zp.lock;/**
 * 描述：
 *
 * @author: 张鹏
 * @Date: ${time} 2018/12/26
 */

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

/**
 * 说明：
 * @author 张鹏
 * @create
 */
public class ZpLock implements Lock {
    private AtomicReference<Thread> owner = new AtomicReference<>();
    private ConcurrentLinkedQueue<Thread> waitThreads = new ConcurrentLinkedQueue<>();
    @Override
    public void lock() {
        boolean flag = true;
        while (!tryLock()){
            if(flag){
                waitThreads.offer(Thread.currentThread());
                flag = false;
            }else{
                // 进入线程等待
                LockSupport.park();
            }
        }
        // 移除等待
        waitThreads.remove(Thread.currentThread());
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        // cas 修改内存操作
        return owner.compareAndSet(null,Thread.currentThread());
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        if(owner.compareAndSet(Thread.currentThread(),null)){
            Thread next = null;
            if((next = waitThreads.peek()) != null){
                LockSupport.unpark(next);
            }
        }
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
